#include "chatpage.h"
#include "ui_chatpage.h"
#include <QStyleOption>
#include <QPainter>
#include "clickedlabel.h"
#include "messageitem.h"
#include <QTimer>
#include <QPropertyAnimation>
#include "usermgr.h"
#include "global.h"
#include <QJsonDocument>
#include "tcpmgr.h"

ChatPage::ChatPage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ChatPage)
{
    ui->setupUi(this);
    //设置图标样式
    ui->file_label->SetState("normal","hover","press","normal","hover","press");
    ui->emo_label->SetState("normal","hover","press","normal","hover","press");
    //设置按钮
    ui->send_btn->SetState("normal","hover","press");
}

ChatPage::~ChatPage()
{
    delete ui;
}

void ChatPage::SetUserInfo(std::shared_ptr<UserInfo> user_info)
{
    _user_info = user_info;
    //设置ui界面
    ui->title_label->setText(_user_info->_name);
    ui->chat_listwidget->removeAllItem();
    auto target_info = UserMgr::GetInstance()->GetFriendById(user_info->_uid);
    if(target_info == nullptr){
        qDebug()<<"ChatPage::SetUserInfo:没有找到该好友";
        return;
    }
    for(auto& msg:target_info->_chat_msgs){
        AppendChatMsg(msg);
    }
//    for(auto& msg:user_info->_chat_msgs){
//        AppendChatMsg(msg);
//    }
}

void ChatPage::AppendChatMsg(std::shared_ptr<TextChatData> msg)
{
    auto self_info = UserMgr::GetInstance()->GetUserInfo();
    if(msg->_from_uid == self_info->_uid){
        MessageItem* msgItem = new MessageItem(true,msg->_msg_content,UserMgr::GetInstance()->GetIcon());
        QListWidgetItem *item = new QListWidgetItem();
        item->setSizeHint(msgItem ->sizeHint());
        ui->chat_listwidget->addItem(item);
        ui->chat_listwidget->setItemWidget(item, msgItem );
    }else{
        auto friend_info = UserMgr::GetInstance()->GetFriendById(msg->_from_uid);
        if(friend_info == nullptr){
            return;
        }
        MessageItem* msgItem = new MessageItem(false,msg->_msg_content,friend_info->_icon);
        QListWidgetItem *item = new QListWidgetItem();
        item->setSizeHint(msgItem ->sizeHint());
        ui->chat_listwidget->addItem(item);
        ui->chat_listwidget->setItemWidget(item, msgItem );
    }
}

void ChatPage::paintEvent(QPaintEvent *event)
{
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget,&opt,&p,this);
    QWidget::paintEvent(event);
}


// 添加一条消息到聊天窗口
void ChatPage::addMessage(bool isSelf, const QString &text,int uid) {
    // 创建自定义消息控件
    MessageItem *msgItem = nullptr;
    if(uid == 0){
        msgItem = new MessageItem(isSelf, text,UserMgr::GetInstance()->GetIcon());
    }else{
        QString icon  = UserMgr::GetInstance()->GetFriendById(uid)->_icon;
        msgItem = new MessageItem(isSelf, text,icon);
    }

    // 创建 QListWidgetItem
    QListWidgetItem *item = new QListWidgetItem();
    item->setSizeHint(msgItem ->sizeHint()); // 自动调整条目高度

    // 添加到列表并关联控件
    ui->chat_listwidget->addItem(item);
    ui->chat_listwidget->setItemWidget(item, msgItem );

    // 确保消息条目已显示后再触发动画
    QTimer::singleShot(10, [=]() { // 延迟 10ms 确保布局完成
        // 创建位置动画（从右侧滑入）
        QPropertyAnimation *anim = new QPropertyAnimation(msgItem, "pos");
        anim->setDuration(300); // 动画时长 300ms
        anim->setStartValue(QPoint(ui->chat_listwidget->width(), msgItem->y())); // 从右侧外开始
        anim->setEndValue(msgItem->pos()); // 滑动到实际位置
        anim->setEasingCurve(QEasingCurve::OutQuad); // 平滑缓动效果
        anim->start(QAbstractAnimation::DeleteWhenStopped); // 自动销毁
    });

    // 自动滚动到底部
    ui->chat_listwidget->scrollToBottom();
}

void ChatPage::on_send_btn_clicked()
{
//    QString text = ui->chat_edit->toPlainText();
//    ui->chat_edit->clear();
//    addMessage(true,text);
    if(_user_info == nullptr){
        qDebug()<<"当前用户为空";
        return;
    }
    std::shared_ptr<UserInfo> user_info = UserMgr::GetInstance()->GetUserInfo();
    QString user_name = user_info->_name;
    QString user_icon = user_info->_icon;
    QJsonObject textObj;

    textObj["fromuid"] = user_info->_uid;
    textObj["touid"] = _user_info->_uid;
    textObj["text"] = ui->chat_edit->toPlainText();
    addMessage(true,ui->chat_edit->toPlainText());

    std::shared_ptr<TextChatData>textdata = std::make_shared<TextChatData>("0",ui->chat_edit->toPlainText(),
                                                                             user_info->_uid,_user_info->_uid);
    _user_info->_chat_msgs.push_back(textdata);
    std::shared_ptr<FriendInfo> self = UserMgr::GetInstance()->GetFriendById(_user_info->_uid);
    self->_chat_msgs.push_back(textdata);

    ui->chat_edit->clear();
    QJsonDocument jsonDoc(textObj);
    QByteArray jsonData = jsonDoc.toJson(QJsonDocument::Compact);
    emit TcpMgr::GetInstance()->sig_send_data(ReqId::ID_TEXT_CHAT_MSG_REQ,jsonData);
}
